package com.redisson_lock;

import com.lock.Lock_tryLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@Service
public class Girl implements Runnable{
    private int num = 1;
    private int size = 20;

    @Autowired
    private RLockUtil lockUtil;
    private String lockKey = "thread:lock:girl";




    @Override
    public void run() {

        while (true) {

            this.start();
        }

    }
    public  void start(){
        Boolean b = lockUtil.reentranTryLock(lockKey);

        if(lockUtil.reentranTryLock(lockKey)) {
            if (num >= size) {
                System.out.println("sell end");
                while (Thread.currentThread().isAlive()) {
                    System.out.println(Thread.currentThread().isInterrupted());
                    System.out.println(Thread.currentThread().isAlive());
                    System.out.println("back girl:" + Thread.currentThread().getName());
                    Thread.currentThread().stop();
                    Thread.currentThread().interrupt();
                    System.out.println(Thread.currentThread().isInterrupted());
                    System.out.println(Thread.currentThread().isAlive());
                    break;
                }
                return;

            }


            try {


                System.out.println(Thread.currentThread().getName() + "lock");


                System.out.println(String.format("date:%s,girl:%s，" +
                        "\'maichu:\'%s ticket ，" +
                        "\'kucun:\'%s ticket",
                        new Date(), Thread.currentThread().getName(), this.num, this.size - this.num));
                Thread.sleep(1000);
                num++;

            } catch (Exception e) {
                e.printStackTrace();

            } finally {
                lockUtil.unReentranLock(lockKey);
                System.out.println(Thread.currentThread().getName() + "unlock");
            }
        }
    }

    public static void main(String[] args) {
        Girl three = new Girl();
        while (true){
            System.out.println("input girl:");
            String girl  = new Scanner(System.in).next();

            Thread thread = new Thread(three,girl);
            thread.start();

        }
    }
}
